import React from 'react';
import {BaseProps} from "../../App";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import IconButton from "@material-ui/core/IconButton";
import Typography from "@material-ui/core/Typography";
import {
    AppsRounded,
    ChevronRightRounded, ExitToAppRounded,
    GridOnRounded,
    MenuRounded,
    VideoLabelRounded
} from "@material-ui/icons";
import SwipeableDrawer from "@material-ui/core/SwipeableDrawer";
import './home.css'
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import {Token} from "../../framework/Token";
import {MenuItem} from "@material-ui/core";
import Select from "@material-ui/core/Select";
import FormControl from "@material-ui/core/FormControl";
import InputBase from "@material-ui/core/InputBase";
import withStyles from "@material-ui/core/styles/withStyles";
import {ProjectModel} from "../model/ProjectModel";
import {ProjectApi} from "../../framework/api/ProjectApi";
import Button from "@material-ui/core/Button";

interface HomeState {
    menuOpen: any;
    location?: any;
    breadcrumbs: any;
    projects: Array<ProjectModel>;
}

interface HomeProps extends BaseProps {
    location?: any;
    history?: any;
}

const BootstrapInput = withStyles((theme) => ({
    root: {
        'label + &': {
            marginTop: theme.spacing(3),
        },
    },
    input: {
        borderRadius: 4,
        position: 'relative',
        backgroundColor: '#ffffff',
        fontSize: 16,
        padding: '10px 26px 10px 12px',
        transition: theme.transitions.create(['border-color', 'box-shadow']),
        // Use the system font instead of the default Roboto font.
        fontFamily: [
            '-apple-system',
            'BlinkMacSystemFont',
            '"Segoe UI"',
            'Roboto',
            '"Helvetica Neue"',
            'Arial',
            'sans-serif',
            '"Apple Color Emoji"',
            '"Segoe UI Emoji"',
            '"Segoe UI Symbol"',
        ].join(','),
        '&:focus': {
            borderRadius: 4,
            borderColor: '#ffffff',
            backgroundColor: '#ffffff'
        },
    },
}))(InputBase);

interface ProjectSelectionProps extends BaseProps {
    projects: Array<ProjectModel>;
    onChange: any;
}

interface ProjectSelectionState {
    currentProject: ProjectModel | null;
}

class ProjectSelection extends React.Component<ProjectSelectionProps, ProjectSelectionState> {
    constructor(props: ProjectSelectionProps) {
        super(props);
        this.state = {
            currentProject: this.props.projects.length === 0 ? null : this.props.projects[0]
        }
    }

    render(): React.ReactElement | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
        if (this.props.projects.length === 0) {
            return <div/>
        }
        return <FormControl className={'toolbar-project-select'}>
            <Select value={this.props.projects[0].id}
                    input={<BootstrapInput/>} onChange={this.props.onChange}>
                {this.props.projects.map((item, index) => (
                    <MenuItem key={index} value={item.id}>{item.name}</MenuItem>))}
            </Select>
        </FormControl>
    }
}

export class Home extends React.Component<HomeProps, HomeState> {

    constructor(props: HomeProps) {
        super(props);
        this.openMenu = this.openMenu.bind(this);
        this.closeMenu = this.closeMenu.bind(this);
        this.logOut = this.logOut.bind(this);
        this.projectChanged = this.projectChanged.bind(this);
        this.createProjectBtn = this.createProjectBtn.bind(this);
        this.state = {
            menuOpen: false,
            breadcrumbs: [],
            projects: []
        }
    }

    componentDidMount(): void {
        ProjectApi.list().then(projects => {
            this.setState({
                projects: projects
            })
        })
    }

    user = Token.user();

    openMenu() {
        this.setState({
            menuOpen: true
        })
    }

    closeMenu() {
        this.setState({
            menuOpen: false
        })
    }

    logOut() {
        Token.logout();
        window.location.reload();
    }

    projectChanged(e: any) {
        console.log(e.target.value)
    }

    createProjectBtn() {
        this.props.history.push("/projects/create")
    }

    menuItems = [
        {name: '配置', path: '/config', icon: (<VideoLabelRounded/>)},
        {name: '组件', path: '/components', icon: (<VideoLabelRounded/>)},
        {name: '服务', path: '/services', icon: (<GridOnRounded/>)}
    ];

    render() {
        return <div>
            <AppBar position="static" color={'inherit'}>
                <Toolbar variant="dense" className={'menu-tool-bar'}>
                    <div className={"toolbar-items"}>
                        <IconButton edge="start" color="inherit" aria-label="menu" onClick={this.openMenu}>
                            <MenuRounded/>
                        </IconButton>
                        <IconButton onClick={() => {
                            this.props.history.push("/" + this.props.match.params.projectId+"/home")
                        }}>
                            <Typography variant="h6" color="inherit">
                                应用中心
                            </Typography>
                        </IconButton>
                        <ProjectSelection projects={this.state.projects} onChange={this.projectChanged}/>

                    </div>
                    <div>
                        <Button color='primary' onClick={this.createProjectBtn}>新建</Button>
                        {this.user?.nickName}<IconButton color="inherit"
                                                         onClick={this.logOut}><ExitToAppRounded/></IconButton>
                    </div>
                </Toolbar>
            </AppBar>
            {/* 菜单栏 */}
            <React.Fragment key={'menuFragment'}>
                <SwipeableDrawer
                    anchor={'left'}
                    open={this.state.menuOpen}
                    onClose={this.closeMenu}
                    onOpen={this.openMenu}>
                    <div className={'menu-content'}>
                        <List>
                            {this.menuItems.map((menu, index) => {
                                return <ListItem key={index} button onClick={() => {
                                    if (this.props.location.pathname === menu.path) {
                                        this.setState({menuOpen: false});
                                    } else {
                                        this.props.history.push("/"+this.props.match.params.projectId+menu.path);
                                        this.setState({menuOpen: false});
                                    }
                                }}>
                                    <ListItemIcon>{menu.icon}</ListItemIcon>
                                    <ListItemText primary={(<Typography>{menu.name}</Typography>)}></ListItemText>
                                    <ListItemIcon
                                        className={'menu-item-icon-right'}><ChevronRightRounded/></ListItemIcon>
                                </ListItem>
                            })}
                        </List>
                    </div>
                </SwipeableDrawer>
            </React.Fragment>
        </div>
    }
}
